package logger

import (
	"fmt"
	"path/filepath"
	"sort"
	"strings"

	log "github.com/sirupsen/logrus"
)

// 行内日志格式化 Format:time,level, message, key1=value, key2=value........,file,line
type Formatter struct{}

func (s *Formatter) Format(entry *log.Entry) ([]byte, error) {
	// 系统标识
	prefix := "_mst_"
	// 错误级别
	level := strings.ToUpper(entry.Level.String())
	// 时间
	timestamp := entry.Time.Local().Format("2006-01-02 15:04:05.000")
	// 包名
	var funcName string
	// 包行数
	var line int
	if entry.HasCaller() {
		funcName = filepath.Base(entry.Caller.Function)
		line = entry.Caller.Line
	}
	message := entry.Message

	FieldsStr := ""

	keys := []string{}
	for k := range entry.Data {
		keys = append(keys, k)
	}

	sort.Slice(keys, func(i, j int) bool {
		return keys[i] < keys[j]
	})

	for _, k := range keys {
		v := entry.Data[k]
		switch v.(type) {
		case int:
			FieldsStr += fmt.Sprintf("%s=%d, ", k, v)
		case string:
			FieldsStr += fmt.Sprintf("%s=%s, ", k, v)
		case bool:
			FieldsStr += fmt.Sprintf("%s=%t, ", k, v)
		default:
			FieldsStr += fmt.Sprintf("%s=%+v, ", k, v)
		}
	}
	msg := fmt.Sprintf("%s,%s,%s, %s, %s%s,%d\n", prefix, timestamp, level, message, FieldsStr, funcName, line)

	return []byte(msg), nil
}
